[英]How to draw behind an image in canvas?
I am using canvas for a picture crop feature and I cannot figure out how to fill the empty spaces.我正在使用 canvas 进行图片裁剪功能,但我不知道如何填充空白区域。
First, this is what I'm doing:首先,这就是我正在做的事情:
Canvas element: Canvas 元件:
<canvas
id="previewCanvas"
ref={previewCanvasRef}
style={{
border: '1px solid black',
objectFit: 'contain',
width: '300px',
height: '300px',
}}
/>
This is the function I use to draw the image:这是我用来绘制图像的 function:
const TO_RADIANS = Math.PI / 180;
export async function canvasPreview(image, canvas, crop, scale = 1, rotate = 0) {
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('No 2d context');
}
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
// devicePixelRatio slightly increases sharpness on retina devices
// at the expense of slightly slower render times and needing to
// size the image back down if you want to download/upload and be
// true to the images natural size.
const pixelRatio = window.devicePixelRatio;
// const pixelRatio = 1
canvas.width = Math.floor(crop.width * scaleX * pixelRatio);
canvas.height = Math.floor(crop.height * scaleY * pixelRatio);
ctx.scale(pixelRatio, pixelRatio);
ctx.imageSmoothingQuality = 'high';
const cropX = crop.x * scaleX;
const cropY = crop.y * scaleY;
const rotateRads = rotate * TO_RADIANS;
const centerX = image.naturalWidth / 2;
const centerY = image.naturalHeight / 2;
ctx.save();
// 5) Move the crop origin to the canvas origin (0,0)
ctx.translate(-cropX, -cropY);
// 4) Move the origin to the center of the original position
ctx.translate(centerX, centerY);
// 3) Rotate around the origin
ctx.rotate(rotateRads);
// 2) Scale the image
ctx.scale(scale, scale);
// 1) Move the center of the image to the origin (0,0)
ctx.translate(-centerX, -centerY);
ctx.drawImage(
image,
0,
0,
image.naturalWidth,
image.naturalHeight,
0,
0,
image.naturalWidth,
image.naturalHeight
);
ctx.restore();
}
This is how I see the canvas on the browser:这就是我在浏览器上看到 canvas 的方式:
Now, when I convert the image to a blob, then to a file object, I get an image like this:现在,当我将图像转换为 blob,然后转换为文件 object 时,我得到如下图像:
What I expect to happen is to get an image like this: (exactly like in the preview)我期望发生的是得到这样的图像:(就像在预览中一样)
What am I doing wrong?我究竟做错了什么?
you can follow the StackOverflow link: https://stackoverflow.com/questions/15457619/html-canvas-drawing-grid-below-a-plot
您可以点击 StackOverflow 链接:
https://stackoverflow.com/questions/15457619/html-canvas-drawing-grid-below-a-plot
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.