如何正确渲染屏幕外画布

时间:2017-04-12 12:36:44

标签: html5 canvas html5-canvas

我正在尝试创建一个离线渲染画布的基本示例,但我在js中的错误“无法读取上下文的属性”。实际上我的想法是创建一个像我在https://yalantis.com/中看到的演示我想创建我的名字的首字母。如果有任何更好的想法来实现这一点,请赐教。 谢谢,这是我在实际实施之前的基本尝试:)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Off Screen Canvas</title>
<script>
    function createOffscreenCanvas() {
        var offScreenCanvas= document.createElement('canvas');
        offScreenCanvas.width= '1360px';
        offScreenCanvas.height= '400px';
        var context= offScreenCanvas.getContext("2d");
        context.fillRect(10,10,200,200);
    }
    function copyToOnScreen(offScreenCanvas) {
        var onScreenContext=document.getElementById('onScreen').getContext('2d');
        var offScreenContext=offScreenCanvas.getContext('2d');
        var image=offScreenCanvas.getImageData(10,10,200,200);
        onScreenContext.putImageData(image,0,0);
    }
    function main() {
        copyToOnScreen(createOffscreenCanvas());
    }
</script>
<style>
    #onScreen {
        width:1360px;
        height: 400px;
    }
</style>
</head>  
 <body onload="main()">
 <canvas id="onScreen"></canvas>
 </body>
</html>

2 个答案:

答案 0 :(得分:2)

你可以通过以下方式实现这一目标......

&#13;
&#13;
function createOffscreenCanvas() {
    var offScreenCanvas = document.createElement('canvas');
    offScreenCanvas.width = '1360';
    offScreenCanvas.height = '400';
    var context = offScreenCanvas.getContext("2d");
    context.fillStyle = 'orange'; //set fill color
    context.fillRect(10, 10, 200, 200);
    return offScreenCanvas; //return canvas element
}

function copyToOnScreen(offScreenCanvas) {
    var onScreenContext = document.getElementById('onScreen').getContext('2d');
    onScreenContext.drawImage(offScreenCanvas, 0, 0);
}

function main() {
    copyToOnScreen(createOffscreenCanvas());
}
&#13;
canvas {
  border: 1px solid black;
}
&#13;
<body onload="main()">
<canvas id="onScreen" width="1360" height="400"></canvas>
&#13;
&#13;
&#13;

注意: 永远不会使用css设置画布的宽度和高度。而是使用画布的原生宽度和高度属性。

答案 1 :(得分:0)

在您的函数offScreenCanvas

中返回createOffscreenCanvas
function createOffscreenCanvas() {
    var offScreenCanvas= document.createElement('canvas');
    offScreenCanvas.width= '1360px';
    offScreenCanvas.height= '400px';
    var context= offScreenCanvas.getContext("2d");
    context.fillRect(10,10,200,200);
    return offScreenCanvas;
}

修改

您从画布获取图像日期而非上下文。

function copyToOnScreen(offScreenCanvas) {
    var onScreenContext=document.getElementById('onScreen').getContext('2d');
    var offScreenContext = offScreenCanvas.getContext('2d');
    var image=offScreenContext.getImageData(10,10,200,200);
    onScreenContext.putImageData(image,0,0);
}