【问题标题】:i want to draw a rectangle on an image in angular2我想在 angular2 的图像上绘制一个矩形
【发布时间】:2017-07-28 21:51:24
【问题描述】:

我有一个从 url 获取的图像。我想在这张图片上画一个矩形。我目前正在尝试使用画布来实现这一点,但我并不完全理解如何实现它。当我使用此代码时,画布中没有任何变化,它保持空白。

我的 html 中有这个

 <canvas #layout></canvas>

然后这个在我的组件打字稿文件中

@ViewChild('layout') canvasRef;

//other code here

drawRectangle(file: any): void
{
    let canvas = this.canvasRef.nativeElement;
    let context = canvas.getContext('2d');

    let source = new Image();
    source.src = this.imgUrl;

    source.onload = () =>
    {
        context.drawImage(source.src,0,0);
        context.beginPath();
        context.rect(file.left, file.top, file.width, file.height);
        context.stroke();  
    };


}

【问题讨论】:

  • ....会发生什么?
  • @putonspectacles 没有任何反应
  • 更新您的问题以反映“什么都没有发生”的含义。也看看我的回答

标签: angular html5-canvas


【解决方案1】:

尝试在更新source.src 之后添加onload() 回调。您还需要将图像 (source) 传递给 drawImage 而不是 source.src 所以这是更新后的代码:

所以

@ViewChild('layout') canvasRef;

//other code here

drawRectangle(file: any): void
{
    let canvas = this.canvasRef.nativeElement;
    let context = canvas.getContext('2d');

    let source = new Image();

    source.onload = () =>
    {
        context.drawImage(source, 0, 0);
        context.beginPath();
        context.rect(file.left, file.top, file.width, file.height);
        context.stroke();  
    };

    source.src = this.imgUrl;




}

【讨论】:

  • 它给出了一个错误,在“CanvasRenderingContext2D”上执行“drawImage”失败:提供的值不是类型“(CSSImageValue or HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)”
  • 试试更新后的代码,我把source.src换成了drawImage调用中的source
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2017-06-09
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多