【问题标题】:how to crop an image (frame) within canvas如何在画布内裁剪图像(框架)
【发布时间】:2017-06-08 21:40:12
【问题描述】:

我在一张图片中有多个帧。如何在画布内绘制图像的裁剪部分?

Party pooper 是画布被拉伸并通过 CSS 响应。示例:

说,每一帧都是 100x100px,我想画帧“5”。所以我必须在以下位置绘制框架:x100,y200,width100,height 100

我的代码如下所示:

this.ctx = this.canvas.get(0).getContext("2d");
this.ctx.drawImage(this.image, - this.imageWidth * x, - this.imageHeight * y, this.image.width, this.image.height);

我的控制台中的所有值都正确,但结果是千斤顶。我是不是把 drawImage 解释错了?

【问题讨论】:

  • 这必须是画布吗?我看不出原因,你没有画画。为什么不使用 CSS3 精灵?它们就是为此而生的。
  • 两个原因:该功能与滚动绑定,我无法调整我的精灵大小。正确地在响应容器中。
  • 您当然仍然可以使用 CSS sprite,方法是根据响应式容器的大小操作 backgroundPosition
  • 忘了说,backgroundPosition 也有百分比值....

标签: javascript html canvas


【解决方案1】:

你为什么使用负值?

对于“5”,您应该使用:

this.ctx.drawImage(this.image, 100, 100);

或者如果你的精灵大小不合适:

this.ctx.drawImage(this.image, 100, 100, 100, 100);

drawImage 的文档: https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多