使用javascript函数和全局变量进行画布绘制 [英] Canvas drawing using javascript functions and global variables

查看:90
本文介绍了使用javascript函数和全局变量进行画布绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


请问我可以帮忙!我被要求开发一个将在Blackberry上运行的应用程序.但是我不懂Java.由于应用程序需要绘图,因此我选择html5和javascript.然后,我阅读了一些JavaScript教程.但是,当我尝试将其付诸实践时,出现错误,指出"getContext"属性未定义.

是否可以用C#编写?

Hi,
May I get help! I am asked to develop an application that will run on Blackberry. But I don''t knowledge in java. Since the application needs drawing, I opt for html5 and javascript. Then I read some javascript tutorials. But when I try to put it into practice it, I get error saying that the "getContext" attribut is undefined.

Is it possible to write in C#?

var canvasCircle;
var contextCircle;
var x = 400;
var y = 300;
var dx = 2;
var WIDTH = 800;
var HEIGHT = 600;
// the circle wont make any transsformation.
function draw_circle(x, y, r) {
    contextCircle.beginPath();
    contextCircle.arc(x, y, r, 0, 2 * Math.PI, true);
    contextCircle.closePath();
    contextCircle.stroke();
}
function clear_canvas() {
    contextCircle.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
    canvasCircle = document.getElementById("canvas_circle");
    contextCircle = canvasCircle.getContext('2d');
    return setInterval(draw, 10);
}
function draw() {
    clear_canvas();
    draw_circle(x, y, 50);
    if (x + dx > WIDTH || x + dx < 0)
        dx = -dx;
    x += dx;
}
init();


<canvas id="canvas_circle" width="800" height="600"></canvas>

推荐答案

您应该检查浏览器中的内容是否正常:

You should check if things work in the browser:

function init() {
    canvasCircle = document.getElementById("canvas_circle");
    if(canvasCircle && canvasCircle.getContext) {
        contextCircle = canvasCircle.getContext('2d');
        return setInterval(draw, 10);
    } else {
        alert('No canvas!');
    }
}



这里的if语句检查是否已找到canvasCircle,以及getContext函数是否可用.

init仅应在页面已加载或可能无法找到canvas元素时调用-replace



The if statement here checks if canvasCircle has been found, and if the getContext function is available.

init should only be called when the page has loaded or it may not be able to find the canvas element - replace

init();




with

window.onload=init;


您需要在通话中使用双引号到getContext:
You need double quotes in your call to getContext:
contextCircle = canvasCircle.getContext("2d");



画布是客户端元素,C#不适用于它们.我猜你可以试试Silverlight.



Canvas are client side elements and C# will not work for them. You could try silverlight I suppose.


这篇关于使用javascript函数和全局变量进行画布绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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