javascript - 将 Javascript 代码与 HTML Canvas 分开

标签 javascript html canvas

我正在尝试学习 HTML5 Canvas,它是从 javascript 代码中绘制的。

看来我无法将 Javascript 代码与原始 html 分开。 一直在寻找一些解决方案:

这些对我来说并不是一个解决方案,因为在我实现这两个解决方案之后,在我看来是空白的 Canvas 。

这是我的代码。

<!DOCTYPE html>
<html>
<head>
    <title>Christoper Hans' Paint HTML5 Project</title>
    <link rel="stylesheet" type="text/css" href="paint.css">
    <script type="text/javascript"><!--
        window.addEventListener('load', function () {
            var ctx = document.getElementById("paint").getContext("2d");
            ctx.canvas.width  = window.innerWidth;
            ctx.canvas.height = window.innerHeight;

            function drawRect(ctx, x1, y1, x2, y2, fill) {

            ctx.fillStyle=fill;
            ctx.fillRect(x1, y1, x2, y2);
            }

            drawRect(ctx, 100, 100, 200, 250, "FF0000");
        }, false);
// --></script>

</head>
<body>
    <canvas id="paint" width="500" height="500" style="border:1px solid #c3c3c3;">
    Your browser does not support the HTML5 canvas tag.
    </canvas>
</body>

我不知道为什么,但只有我从这个网站的帖子中获得的这种代码才有效,而且我无法将 JavaScript 分离到外部文件。

TL;DR:想要将 javascript 与 html 分开以使用 Canvas 。

大家有什么帮助吗?

最佳答案

我不得不猜测您也在复制 <!--// -->到您的外部文件。如果是这样,请不要这样做。您甚至不应该再使用它们,除非您正在迎合上个世纪的浏览器。

关于javascript - 将 Javascript 代码与 HTML Canvas 分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16194047/

相关文章:

android - PorterDuff.Mode.DST_IN 应该透明的地方变黑

javascript - 处理相对于 Canvas 而不是图像可拖动的旋转 Canvas 图像

javascript - 如何将 console.log 作为参数传递给我的 JavaScript 函数?

android - 我可以将使用 Ratchet 构建的应用程序提交到应用程序商店和 Google Play 商店吗?

html - 元素可以粘在 Iframe 上吗?

html - 使用 nth-child() 进行高级元素选择

javascript - jQuery 可排序子项不会进入父项

javascript - 如何在 CodePen 中从外部提供者获取数据?

javascript - 使用 moo 工具的 Fx.Slide 操纵许多滑动对象的最佳方式

javascript - HTML5 Canvas 游戏中的多个 setInterval