1

在按钮上单击我调用脚本来获取画布图像。我拿位置。我需要将此图像源传递到另一个需要显示此图像的 jsp 文件中。

你能帮我解决这个问题吗?

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <script>
        function draw() {
             var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            ctx.fillStyle = "black";
            ctx.beginPath();
            var x;
            var y;
            canvas.onmousedown = function(e) {
                x = e.clientX;
                y = e.clientY;
                ctx.moveTo(x, y);
            }
            canvas.onmouseup = function(e) {
                x = null;
                y = null;
            }
            canvas.onmousemove = function(e) {
                if (x == null || y == null) {
                    return;
                }
                x = e.clientX;
                y = e.clientY;
                x -= canvas.offsetLeft;
                y -= canvas.offsetTop;
                ctx.lineTo(x, y);
                ctx.stroke();
                ctx.moveTo(x, y);
            }
        };
        function to_image(){
            var canvas = document.getElementById("canvas");
            document.getElementById("theimage").src = canvas.toDataURL();
        }
        function clear_image(){
            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');
            context.fillStyle = '#ffffff';
            context.clearRect(0, 0, canvas.width, canvas.height);
            canvas.width = canvas.width;
         }
    </script>
</head>
<body onload="draw();">
<canvas id="canvas" width="300" height="300"
style="border: 1px solid black;"></canvas>
<div><button onclick="to_image()">Draw to Image</button></div>
<div><button onclick="clear_image()">Clear</button></div>
<image id="theimage"></image>
</body>
</html>

我需要将 document.getElementById("theimage").src 的值传递到另一个 jsp 并访问该值以显示图像。

任何人都可以帮助我解决这个问题。

4

1 回答 1

0

如果您的意思是您将在从第一页(您已粘贴代码)单击按钮上加载带有图像的第二页,那么只需将代码更新为:

    {

        var canvas = document.getElementById("canvas");
        var dataUrl = canvas.toDataURL();

        //-- Following code can be placed wherever you want to call another page.
        window.location = "urlToSecondJSPPage.jsp?imgUrl="+dataUrl;

    }

然后可以从第二页访问 imgUrl(url 参数)。

于 2012-10-26T06:50:34.513 回答