【问题标题】:How to rescale image to draw with canvas?如何重新缩放图像以使用画布绘制?
【发布时间】:2017-11-22 14:20:49
【问题描述】:

如果你有想法, 从本帖的代码开始In javascript , how to reverse y axis of canvas?(用Flip渲染内容解决方案) 我想在 100*100 画布中绘制最后一张图像(200*200),使用 ctx.drawImage(ctx.canvas,0,0,200,200,0,0,100,100) 重新缩放它,但它只会裁剪它 问候

【问题讨论】:

    标签: javascript image canvas rescale


    【解决方案1】:

    在绘制之前将上下文缩放 0.5。

    ctx.scale(0.5,0.5)
    

    var i,j;
    const n = 200;
    const size = n ** 2;  // ** is to power of
    //const canvas = document.querySelector('canvas'); // not needed canvas is 
                                                       // already defined with 
                                                       // id="canvas"
    const ctx = canvas.getContext("2d");
    const imgData = ctx.createImageData(n, n);
    const Z = [];
    for (j = 0; j < size; j ++) { Z[j] = j * 256 / size }
    Z[n * n - 1] = 0;
    i = 0;
    for (j = 0; j < size; j++) {
      imgData.data[i++] = Z[j];
      imgData.data[i++] = Z[j];
      imgData.data[i++] = Z[j];
      imgData.data[i++] = 255;
    }
    ctx.putImageData(imgData, 0, 0);
    ctx.scale(0.5,0.5);
    // flip the canvas
    ctx.transform(1, 0, 0, -1, 0, canvas.height)
    ctx.globalCompositeOperation = "copy"; // if you have transparent pixels
    ctx.drawImage(ctx.canvas,0,0);
    ctx.globalCompositeOperation = "source-over"; // reset to default
    &lt;canvas id="canvas" width=200 height=200&gt;&lt;/canvas&gt;

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多