英文:
Paste a image to the canvas for full size
问题
我有一张 640x692 的 jpg 图片(Emperor_Penguin_Manchot_empereur.jpg)。我想要将它粘贴到画布上。
所以,我创建了画布:
const canvasRef = useRef();
useEffect(() => {
var chara = new Image();
chara.src = "http://localhost:8021/Emperor_Penguin_Manchot_empereur.jpg";
chara.onload = () => {
var ctx = canvasRef.current.getContext('2d');
ctx.drawImage(chara, 0, 0, 640, 692, 0, 0, 640, 692);// 将图像以相同大小粘贴。
}
}, []);
return (
<canvas ref={canvasRef} style={{ width: 640, height: 692 }}></canvas>
);
这是图片:
结果:
然而,使用这个脚本,它只显示了图片的一部分(左上角)。
我将画布和 jpg 的大小设置成了一样的。
我错在哪里?
英文:
I have 640x692 jpg (Emperor_Penguin_Manchot_empereur.jpg). and I want to paste this in canvas.
So, I made the canvas
const canvasRef = useRef();
useEffect(() =>{
var chara= new Image();
chara.src = "http://localhost:8021/Emperor_Penguin_Manchot_empereur.jpg";
chara.onload = () => {
var ctx = canvasRef.current.getContext('2d');
ctx.drawImage(chara,0,0,640,692,0,0,640,692);// paste the image as the same size.
}
return
<canvas ref={canvasRef} style={{width:640,height:692}}></canvas>
this is the picture,
result
However with this script, it shows the only the part of this picture (left top).
I set the size of canvas and jpg as the same size.
Where am I wrong??
答案1
得分: 1
你需要明确定义你的画布的尺寸/分辨率,例如:
<canvas ref={canvasRef} width={640} height={692}></canvas>
如果不这样做,浏览器会使用一些默认值,如300像素 × 150像素。你的CSS只是拉伸画布至640像素 × 692像素,它并不会实际增加画布的分辨率。
英文:
You need to explicitly define your canvas's dimensions/resolution, e.g.:
<canvas ref={canvasRef} width={640} height={692}></canvas>
Without it, the browser uses some default like, 300px × 150px. All your CSS does is stretch the canvas to be 640px × 692px, it doesn't actually make the canvas resolution larger.
答案2
得分: 1
代码中存在一些错误。首先,没有将画布的宽度和高度设置为图像的宽度和高度。这导致了图像被缩放以适应画布。其次,没有为画布创建一个新的2D上下文。这导致图像使用默认的2D上下文绘制到画布上,这并不总是你想要的。
const canvasRef = useRef();
useEffect(() => {
const chara = new Image();
chara.src = "http://localhost:8021/Emperor_Penguin_Manchot_empereur.jpg";
chara.onload = () => {
const ctx = canvasRef.current.getContext('2d');
ctx.drawImage(chara, 0, 0);
};
}, []);
return (
<canvas ref={canvasRef} style={{width: 640, height: 692}} />
);
英文:
The code has a few errors. First, does not set the canvas's width and height to the image's width and height. This resulted in the image being scaled to fit the canvas. Second, it does not create a new 2D context for the canvas. This resulted in the image being drawn to the canvas using the default 2D context, which is not always what you want.
const canvasRef = useRef();
useEffect(() => {
const chara = new Image();
chara.src ="http://localhost:8021/Emperor_Penguin_Manchot_empereur.jpg";
chara.onload = () => {
const ctx = canvasRef.current.getContext('2d');
ctx.drawImage(chara, 0, 0);
};
}, []);
return (
<canvas ref={canvasRef} style={{width: 640, height: 692}} />
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论