1
好吧,所以我知道有一個類似的帖子(javascript erase image with cursor),但我已經看到它和代碼鏈接在答案中,我想知道是否有一種方法來編輯the code,這樣,而不是擦除純色爲了顯示圖像,我可以擦除圖像以顯示不同的圖像。如何用光標清除圖像以顯示其他圖像?
這是該網站的代碼/標記。
HTML
<div id="canvas"></div>
CSS
#canvas {
background:url(http://www.topscratchcards.com/images/games/888ladies/scratchcard-winning-ticket.jpg);
width: 531px;
height: 438px;
}
JAVASCRIPT
(function() {
// Creates a new canvas element and appends it as a child
// to the parent element, and returns the reference to
// the newly created canvas element
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}
function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var radius = 20; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
}
var container = document.getElementById('canvas');
init(container, 531, 438, '#ddd');
})();
我不知道是否有編輯此代碼,以達到我想要的方式 - 如果有是不是有沒有其他方法/我可以使用的代碼?
謝謝你去答案。但是這不會立即改變圖像,而不是用光標擦去前面的圖像(少量) – StarryKnight