如何正确渲染屏幕外的画布 [英] how to render offscreen canvas properly

查看:136
本文介绍了如何正确渲染屏幕外的画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a basic example of offscreen rendering canvas but I'm error in js "cannot read property of context". actually my idea is to create a demo like I saw in https://yalantis.com/ I want to create my name initial. If there is any better idea to achieve this then please enlighten me. Thanks here is my basic attempt before the actual implementation :)

<!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>


推荐答案

您可以通过以下方式实现此目的......

You could achieve this in the following way ...

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());
}

canvas {
  border: 1px solid black;
}

<body onload="main()">
<canvas id="onScreen" width="1360" height="400"></canvas>

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

note : never set canvas's width and height using css. instead use the native width and height property of the canvas.

这篇关于如何正确渲染屏幕外的画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆