gpt4 book ai didi

javascript - 当我绘制边界框时, Canvas 内渲染的图像消失了?

转载 作者:行者123 更新时间:2023-12-03 00:24:23 27 4
gpt4 key购买 nike

我正在尝试在 Canvas 上渲染的图像上绘制边界框。但是一旦我绘制边界框,图像就消失了。谁能帮我解决这个问题,引用我的以下代码:

<body>
<canvas id="canvas1" width="300" height="300"></canvas>

<script>
var canv = document.getElementById('canvas1'),
ctx = canv.getContext('2d'),
rect = {},
drag = false;

function draw() {
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
}

function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}

function mouseUp() {
drag = false;
}

function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY ;
ctx.clearRect(0, 0, canv.width, canv.height);
draw();
}
}

function init() {
canv.addEventListener('mousedown', mouseDown, false);
canv.addEventListener('mouseup', mouseUp, false);
canv.addEventListener('mousemove', mouseMove, false);
}

function loadImage(canvas, context){
var img = new Image();
img.onload = function(){
context.drawImage(img, 0, 0, img.width, img.height,
0, 0, canvas.width, canvas.height );
};
img.src = "./Pics/img3.png";
}

init();
loadImage(canv, ctx);

</script>
</body>

注意:我正在渲染尺寸(宽度和高度)大于 Canvas 的图像

最佳答案

这就是您的代码要求执行的操作,

ctx.clearRect(0, 0, canv.width, canv.height); // This clears the canvas
draw();

为了避免这种情况,您必须从 draw() 方法中再次调用 ctx.drawImage()

但最好的方法可能是在启动应用程序的任何内容之前等待图像加载完毕,这样,img.onload 将负责告知 Assets 何时准备就绪,并且您将能够使用该图像绘图应用程序的初始化。

var canv = document.getElementById('canvas1'),
ctx = canv.getContext('2d'),
rect = {},
drag = false,
img = loadImage(init); // pass the init function as a callback

function loadImage(cb)  {
var img = new Image();
img.onload = cb;
img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
return img;
}

function draw() {
ctx.clearRect(0, 0, canv.width, canv.height); // clear
ctx.drawImage(img, -200, -100); // draw bg
drawRect(); // draw rect
}

function drawRect() {
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
}

function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}

function mouseUp() {
drag = false;
}

function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
draw();
}
}

function init() {
canv.addEventListener('mousedown', mouseDown, false);
canv.addEventListener('mouseup', mouseUp, false);
canv.addEventListener('mousemove', mouseMove, false);
draw();
}
<canvas id="canvas1" width="300" height="300"></canvas>

关于javascript - 当我绘制边界框时, Canvas 内渲染的图像消失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54157283/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com