gpt4 book ai didi

javascript - 与用于 Canvas 绘图的javascript中的两个函数冲突

转载 作者:行者123 更新时间:2023-11-29 23:58:23 25 4
gpt4 key购买 nike

有两个不同的函数用于在 Canvas 上绘制自由绘图和线条绘图。但是当调用一个函数时,其他函数无法正常工作。如果先调用画线函数,当我们按下按钮自由绘制时,它也会画线。在相反的情况下,绘制连续线。下面给出了这两个函数。免费绘图

function free(){
var canvas=document.getElementById('canvas');
var radius=10;
var dragging1=false;


context.lineWidth=2*radius;

var putPoint=function(e) {
if(dragging1){
context.lineTo(e.clientX,e.clientY);
context.stroke();
context.beginPath();
context.arc(e.clientX,e.clientY,radius,0,Math.PI*2);
context.fill();
context.beginPath();
context.moveTo(e.clientX,e.clientY);
}//end of if
}

var engage = function(e) {
dragging1=true;
putPoint(e);
}

var disengage = function() {
dragging1=false;
context.beginPath();
}
canvas.addEventListener('mousedown',engage);
canvas.addEventListener('mousemove',putPoint);
canvas.addEventListener('mouseup',disengage);
}

用于画线 函数行(){ 变种 Canvas , 语境, 拖动=假, 拖动开始位置, 快照;

function getCanvasCoordinates(event) {
var x = event.clientX - canvas.getBoundingClientRect().left,
y = event.clientY - canvas.getBoundingClientRect().top;

return {x: x, y: y};
}

function takeSnapshot() {
snapshot = context.getImageData(0, 0, canvas.width, canvas.height);
}

function restoreSnapshot() {
context.putImageData(snapshot, 0, 0);
}


function drawLine(position) {
context.beginPath();
context.moveTo(dragStartLocation.x, dragStartLocation.y);
context.lineTo(position.x, position.y);
context.stroke();
}

function dragStart(event) {
dragging = true;
dragStartLocation = getCanvasCoordinates(event);
takeSnapshot();
}

function drag(event) {
var position;
if (dragging === true) {
restoreSnapshot();
position = getCanvasCoordinates(event);
drawLine(position);
}
}

function dragStop(event) {
dragging = false;
restoreSnapshot();
var position = getCanvasCoordinates(event);
drawLine(position);
}

function init() {
canvas = document.getElementById("canvas");
context = canvas.getContext('2d');
context.strokeStyle = 'purple';
context.lineWidth = 6;
context.lineCap = 'round';

canvas.addEventListener('mousedown', dragStart, false);
canvas.addEventListener('mousemove', drag, false);
canvas.addEventListener('mouseup', dragStop, false);
}
init()
}

我该如何解决这个问题?我卡在这一点上了。

最佳答案

在这种情况下,请创建两个函数来删除另一个函数中的事件监听器。这意味着创建功能

    function removeLineListeners(){
canvas.removeEventListener('mousedown', dragStart);
canvas.removeEventListener('mousemove', drag);
canvas.removeEventListener('mouseup', dragStop);
}

    function removeFreeListeners(){
canvas.removeEventListener('mousedown',engage,false);
canvas.removeEventListener('mousemove',putPoint,false);
canvas.removeEventListener('mouseup',disengage,false);
}

因此,当将 removeLineListeners() 添加到免费和removeFreeListeners() 到 Line 函数的字符串。这对我有用

关于javascript - 与用于 Canvas 绘图的javascript中的两个函数冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41202206/

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