Bre*_*sso 7 html javascript jquery html5 canvas
我编写了一个脚本,允许用户在html 5 canvas元素上绘制简单的线条.最终目标是在浏览器的其余部分平铺和重复绘制此绘图.我已经在页面上获得了一个克隆的画布,但我正在努力如何在多个画布上同时绘制相同的线条.
我将在下面粘贴我的代码
var size = 40;
var md = false;
var canvas = document.getElementById('canvas');
canvas.addEventListener('mousedown', down);
canvas.addEventListener('mouseup', toggledraw);
canvas.width  = 600;
canvas.height = 600;
canvas.addEventListener('mousemove', move);
function move(evt){
  var mousePos = getMousePos(canvas, evt);
  var posx = mousePos.x;
  var posy = mousePos.y;
  draw(canvas, posx, posy);
  window.posx;
  return mousePos;
};
function down(){
  md = true;
}
function toggledraw(){
  md = false;
}
function getMousePos(canvas, evt){
  var rect = canvas.getBoundingClientRect();
  return{
    x:evt.clientX - rect.left,
    y:evt.clientY - rect.top
  };
};
function draw(canvas, posx, posy){
  var context = canvas.getContext('2d');
  if(md){
    context.fillRect(posx, posy, size, size)
  }
};
cloneCanvas(canvas, window.posx, window.posy, size);
function cloneCanvas(canvas, posx, posy, size,) {
  console.log(posx);
  var newCanvas = document.createElement('canvas');
  var context = newCanvas.getContext('2d');
  newCanvas.className = "newNew";
  newCanvas.width = canvas.width;
  newCanvas.height = canvas.height;
  document.body.appendChild(newCanvas);
  //context.fillRect(posx, posy, size, size)
  context.drawImage(canvas, posx, posy);
  return canvas;
}
我的方法是在主画布上绘制后更新克隆画布。
根据您当前的代码,我首先想返回克隆的画布而不是旧的画布。这样你就可以参考它了。
 function cloneCanvas(canvas, posx, posy, size,) {
   ...
 //  --> return canvas;
 return newCanvas // Becomes this.
}
接下来,看看这一行:
cloneCanvas(canvas, window.posx, window.posy, size);
我看到您正在使用自己的“posx”和“posy”变量。我会去掉那些,因为你总是想复制整个画布。(在这种情况下)。像这样改变线路
var clone = cloneCanvas(canvas, 0, 0, size);
接下来,我编写了一个小辅助函数来链接两个画布。
function drawFromSource(source, destination) {
  return function() {
    var context = destination.getContext('2d');
    context.clearRect(0, 0, destination.width, destination.height);
    context.drawImage(source, 0, 0);
  }
}
此函数返回一个回调,调用该回调时会将原始画布绘制到克隆画布上。
你可以像这样初始化它:
var updateClone = drawFromSource(canvas, clone);
最后但并非最不重要的一点是,您必须将新创建的回调添加到绘图函数中。在您在主画布上绘制之后。
function draw(canvas, posx, posy) {
  var context = canvas.getContext('2d');
  if (md) {
    context.fillRect(posx, posy, size, size)
    updateClone();
  }
};
瞧!这是工作代码的链接,我移动了一些代码。
https://jsfiddle.net/30efdvz3/5/
只是为了好玩。平铺版本只需更改“numberofTiles”
https://jsfiddle.net/30efdvz3/3/