【问题标题】:how to draw on a image background using canvas?如何使用画布在图像背景上绘制?
【发布时间】:2018-06-20 17:47:19
【问题描述】:

我的代码有什么问题。我试图在画布上加载图像背景,然后在图像画布上绘制几个矩形。我的图像没有显示在画布上,或者它完全覆盖了我的矩形。
我已经关注了这个SO 问题,但它仍然发生了。

//Initialize a new Box, add it, and invalidate the canvas
function addRect(x, y, w, h, fill) {
  var rect = new Box;
  rect.x = x;
  rect.y = y;
  rect.w = w
  rect.h = h;
  rect.fill = fill;
  boxes.push(rect);
  invalidate();
}

// holds all our rectangles
var boxes = []; 

// initialize our canvas, add a ghost canvas, set draw loop
// then add everything we want to intially exist on the canvas
function drawbackground(canvas,ctx,onload){
  var img = new Image();
  img.onload = function(){
    // canvas.width = img.width;
    // canvas.height = img.height;
    ctx.drawImage(img);
    //addRect(200, 200, 200, 200, '#FFC02B');
    onload(canvas,ctx);
  };
  img.src = "https://cdnimages.opentip.com/full/VLL/VLL-LET-G.jpg";
}

function init() {
  // canvas = fill_canvas();
  canvas = document.getElementById('canvas');
  HEIGHT = canvas.height;
  WIDTH = canvas.width;
  ctx = canvas.getContext('2d');
  ghostcanvas = document.createElement('canvas');
  ghostcanvas.height = HEIGHT;
  ghostcanvas.width = WIDTH;
  gctx = ghostcanvas.getContext('2d');


  // make draw() fire every INTERVAL milliseconds
  setInterval(draw, INTERVAL);

  // set our events. Up and down are for dragging,
  // double click is for making new boxes
  canvas.onmousedown = myDown;
  canvas.onmouseup = myUp;
  canvas.ondblclick = myDblClick;

  // add custom initialization here:
  drawbackground(canvas,ctx);
  //context.globalCompositeOperation = 'destination-atop';
  // add an orange rectangle
  addRect(200, 200, 200, 200, '#FFC02B');

  // add a smaller blue rectangle
  addRect(25, 90, 250, 150  , '#2BB8FF');
}

//wipes the canvas context
function clear(c) {
  c.clearRect(0, 0, WIDTH, HEIGHT);
}
...

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    由于图像总是异步加载,并且您在调用 reductionground() 后同步绘制矩形,您将获得一个只有图像的画布。

    你需要创建一个函数,它将作为第三个参数传递给reakgroundground,并在这个函数中调用addRect而不是detailground

    PS: 您的代码应该抛出异常,因为

    onload(canvas,ctx);
    

    将尝试调用 undefined 作为函数

    【讨论】:

    • 它没有抛出任何异常!!。除了创建一个函数来调用我的 addRect 之外,我可以直接将 addrect 作为第三个参数传递给我的缺点吗?
    • 不,因为detailground调用它的第三个参数有两个参数:onload(canvas,ctx);你应该使用另一个函数(匿名作为选项):drawbackground(canvas,ctx, function() { addRect(200, 200, 200, 200, '#FFC02B'); addRect(25, 90, 250, 150 , '#2BB8FF'); });
    • 我需要在我的新函数中处理传递的参数(canvas,ctx)还是在不接收它们的情况下进行绘制,如上所示。
    • 取决于你的需要,我认为)你可以忽略这些论点,没关系。
    • jsfiddle.net/cpeq3kht 这是我的代码。我无法让它工作。我哪里做错了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2019-04-16
    • 2016-08-05
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多