gpt4 book ai didi

javascript - 绘图应用程序 : turn pixels to grayscale or erase them

转载 作者:行者123 更新时间:2023-11-28 04:34:16 24 4
gpt4 key购买 nike

我有一个绘图应用程序,它由一个带有灰度背景图像的容器组成,在它上面有另一个图像(相同但不是灰度图像)。
当我在图像上绘制时,我会删除绘制的位置或转为灰度(以在背景中再现图像)。
我怎样才能做到这一点?
这是我的代码:

<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#wrapper {
width: 600px;
height: 400px;
border: 1px solid black;
margin: 0 auto;
background-image: url('elephant-nb-400.jpg');
}
</style>
</head>
<body>
<div id="wrapper">
<canvas width="600" height="400"></canvas>
</div>
<script>
window.onload = function() {
var wrapper = document.querySelector("#wrapper");
var canvas = document.querySelector("#wrapper canvas");
var context = canvas.getContext("2d");
var image = document.createElement("img");
image.setAttribute("src", "elephant-400.jpg");
image.onload = function() {
context.drawImage(image, 0, 0, 600, 400);
};

var positionsX = new Array();
var positionsY = new Array();
var movements = new Array();
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
var isErasing;

canvas.addEventListener("mousedown", function(e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
isErasing = true;
addPositions(mouseX, mouseY);
draw();
});

canvas.addEventListener("mousemove", function(e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
if(isErasing) {
addPositions(mouseX, mouseY, true);
draw();
}
});

canvas.addEventListener("mouseup", function(e) {
isErasing = false;
});

var addPositions = function(x, y, isMoving) {
positionsX.push(x);
positionsY.push(y);
movements.push(isMoving);
}

var draw = function(){
//context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas

for(var i=0; i < positionsX.length; i++) {
context.beginPath();
if(movements[i] && i){

}else{

}
context.lineTo(positionsX[i], positionsY[i]);
context.closePath();
context.stroke();
}
}

}


</script>
</body>

最佳答案

我的问题解决了。您需要获取图像数据:var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
在 draw() 函数中,您需要在 context 之后添加:context.putImageData(imageData, 0, 0, positionsX[i]-1, positionsY[i], 20, 20); .moveTo(positionsX[i-1], positionsY[i-1]);context.moveTo(positionsX[i]-1, positionsY[i]);

关于javascript - 绘图应用程序 : turn pixels to grayscale or erase them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41568583/

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