简体   繁体   English

如何使用画布在图像背景上绘制?

[英]how to draw on a image background using canvas?

What is wrong with my code.I am trying to load the image background on a canvas and then draw few rectangles on the image canvas.my image is not showing up on the canvas or either is it being completely overwritten my rectangles. 我的代码有什么问题。我试图将图像背景加载到画布上,然后在图像canvas上绘制几个矩形。我的图像没有显示在画布上,或者它被完全覆盖了我的矩形。
I have followed this SO question, but still, it happens. 我跟了这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);
}
...

As the Image loads always asynchronously, and you draw your rects synchronously after drawbackground() call, you will get a canvas with only image on it. 由于图像始终异步加载,并且在调用drawbackground()之后同步绘制矩形,因此您将获得仅包含图像的画布。

You need to create function which will pe passed as third argument to drawbackground, and call addRect in this function instead of drawbackground 您需要创建将pe作为第三个参数传递给drawbackground的函数,并在此函数中调用addRect而不是drawbackground

PS: Your code should throw an exception because PS:您的代码应引发异常,因为

onload(canvas,ctx);

will try to call undefined as a function 将尝试调用undefined作为函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM