html5-canvas 在线移动对象

2023-06-20前端开发问题
0

本文介绍了html5-canvas 在线移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想在斜线上移动一个对象.我已经给出了我的代码.在我的第三个 div 的代码中,当我移动滑块时,我在这条线上画了一条斜线,我想移动一个对象.我在我的第一个 div 中做类似的事情.我在曲线上移动物体的地方.我正在寻找一些函数,我将在其中提供点并且对象将跟随这些点.这是我的代码.此代码仅适用于 chrome,因为我试图将其仅用于 safari 和 chrome 浏览器.

I want to move a object on a slanting line. I have given my code. In my code in my 3rd div as I move the slider I am drawing a slanting line on this line I want to move an object. Similar thing I am doing in my 1st div. Where I am moving an object on curve. I am looking for some function in which I will provide the points and the object will follow the points. Here is my code. This code works only in chrome as I am trying to make this only for safari and chrome browsers.

        <!DOCTYPE HTML>
            <html>
            <head>

   <style type="text/css">
        .wrapper {
            margin: 0 auto;
            width: 1000px;
        }
        .canHdr {
           float: left;
           width: 450px;
               height: 400px;
               border: 1px solid red;
    }
  </style>

    </head>
    <body>
    <form>
    <!-- wrapper -->
    <div class="wrapper">

        <!-- canHdr -->
        <div id="canHdr" class="canHdr" >

            <p>
                This is my 1st div with bezier curve the curve is getting drawn as slider moves and also a ball in moving on that . 
            </p>

            <div class="canOuterHdr" >
                <canvas id="myCanvas1" width="300" height="195" style="position: relative;">
                    [No canvas support]
                </canvas>

            </div>

            <div id="slider1" class="newBg">
                <input id="slide1" type="range" min="0" max="100" step="1" value="0" onchange="counterSlider('slide1');" />
            </div>

        </div>
        <!--/ canHdr -->
        <!-- canHdr2 -->
        <div id="canHdr2" class="canHdr" >

            <p>
                This is my 2nd div
            </p>

            <div class="canOuterHdr" >
                <canvas id="myCanvas2" width="300" height="195" style="position: relative;">
                    [No canvas support]
                </canvas>

            </div>

            <div id="slider2" class="newBg">
                <input id="slide2" type="range" min="0" max="100" step="1" value="0" onchange="counterSlider('slide2');" />
            </div>

        </div>
        <!-- canHdr2 -->
        <!-- canHdr3 -->
        <div id="canHdr3" class="canHdr" >
            <p>
                This is my 3rd div with slanting line. I want to move a ball on this line when I move the slider. So as the line increases ball will also move on the line.
            </p>

            <div class="canOuterHdr" >
                <canvas id="myCanvas3" width="300" height="195" style="position: relative;">
                    [No canvas support]
                </canvas>

            </div>

            <div id="slider3" class="newBg">
                <input id="slide3" type="range" min="0" max="100" step="1" value="0" onchange=" drawSlopeCurve2('slide3','100'); " />
            </div>

        </div>
        <!--/ canHdr3 -->
        <!-- canHdr4 -->
        <div id="canHdr4" class="canHdr" >

            <p>
                This is my 4th div with slanting line. I want to move a ball on this line when I move the slider. So as the line increases ball will also move on the line.
            </p>

            <div class="canOuterHdr" >
                <canvas id="myCanvas4" width="300" height="195" style="position: relative;">
                    [No canvas support]
                </canvas>

            </div>

            <div id="slider4" class="newBg">
                <input id="slide4" type="range" min="0" max="100" step="1" value="0" onchange=" drawSlopeCurve1('slide4','100'); " />
            </div>

        </div>
        <!--/ canHdr4 -->

    </div>
    <!-- /wrapper -->

    <script type="text/javascript">
        function counterSlider(sID) {

            var slideVal = document.getElementById(sID).value;
            /*if (maxValue ==100){

             slideVal=slideVal/100;
             }*/
            slideVal = slideVal / 100;
            var position = slideVal;

            var startPt = {
                x : 18.8,
                y : 45
            };
            var controlPt = {
                x : 28,
                y : 160
            };
            var endPt = {
                x : 228,
                y : 165
            };
            var startPt2 = {
                x : 20,
                y : 75
            };
            var controlPt2 = {
                x : 28,
                y : 160
            };
            var endPt2 = {
                x : 228,
                y : 165
            };

            if (slideVal == 0) {

                erase('myCanvas2');
                erase('myCanvas3');
                erase('myCanvas4');
                //newSprite('myCanvas1b', 18.8, 45);

                drawBezier2('myCanvas1', new Array({
                    x : 18.8,
                    y : 45
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);
                drawBezier2('myCanvas2', new Array({
                    x : 20,
                    y : 75
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);

            } else if (slideVal > 0 && slideVal <= 34) {

                erase('myCanvas1');
                //erase('myCanvas1b');
                erase('myCanvas2');
                erase('myCanvas3');
                erase('myCanvas4');

                drawBezier2('myCanvas1', new Array({
                    x : 18.8,
                    y : 45
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);
                drawBezier2('myCanvas2', new Array({
                    x : 20,
                    y : 75
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);

                drawNextPoint('myCanvas1', startPt, controlPt, endPt, position);
                drawNextPoint('myCanvas2', startPt2, controlPt2, endPt2, position);

            } else if (slideVal > 34 && slideVal <= 67) {

                erase('myCanvas1');

                erase('myCanvas2');
                erase('myCanvas3');
                erase('myCanvas4');

                drawBezier2('myCanvas1', new Array({
                    x : 18.8,
                    y : 45
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);
                drawBezier2('myCanvas2', new Array({
                    x : 20,
                    y : 75
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);

                drawNextPoint('myCanvas1', startPt, controlPt, endPt, position);
                drawNextPoint('myCanvas2', startPt2, controlPt2, endPt2, position);

            } else if (slideVal > 67 && slideVal <= 100) {

                erase('myCanvas1');

                erase('myCanvas2');
                erase('myCanvas3');
                erase('myCanvas4');

                drawBezier2('myCanvas1', new Array({
                    x : 18.8,
                    y : 45
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);
                drawBezier2('myCanvas2', new Array({
                    x : 20,
                    y : 75
                }, {
                    x : 28,
                    y : 160
                }, {
                    x : 228,
                    y : 165
                }), slideVal);

                drawNextPoint('myCanvas1', startPt, controlPt, endPt, position);
                drawNextPoint('myCanvas2', startPt2, controlPt2, endPt2, position);

            }
        }

        function erase(canvasId) {

            var canvas = document.getElementById(canvasId);
            var context = canvas.getContext("2d");
            context.beginPath();
            context.clearRect(0, 0, canvas.width, canvas.height);
            canvas.width = canvas.width;

        }


        /**********for backgroundImage********************/

        function _getQBezierValue(t, p1, p2, p3) {
            var iT = 1 - t;
            return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;

        }

        function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
            return {
                x : _getQBezierValue(position, startX, cpX, endX),
                y : _getQBezierValue(position, startY, cpY, endY)
            };
        }

        function drawNextPoint(canId, startPt, controlPt, endPt, position) {
            var pt = getQuadraticCurvePoint(startPt.x, startPt.y, controlPt.x, controlPt.y, endPt.x, endPt.y, position);
            position = (position + 0.006) % 1.0;
            var canvas = document.getElementById(canId);
            var ctx = canvas.getContext('2d');
            //ctx.globalCompositeOperation = 'source-atop';
            //ctx.globalCompositeOperation = "destination-over";
            ctx.beginPath();
            ctx.fillStyle = "#0077c1";
            ctx.arc(pt.x, pt.y, 6, 0, Math.PI * 2, true);
            ctx.closePath();
            ctx.fill();
        }

        function newSprite(canId, mvx, mvy) {
            var canvas = document.getElementById(canId);
            var ctx = canvas.getContext('2d');
            ctx.globalCompositeOperation = 'source-atop';
            //ctx.globalCompositeOperation = "destination-over";
            ctx.beginPath();
            ctx.fillStyle = "#0077c1";
            ctx.arc(mvx, mvy, 6, 0, Math.PI * 2, true);
            ctx.closePath();
            ctx.fill();
        }

        function drawBezier2(canId, points, slideVal) {

            var canvas = document.getElementById(canId);

            var context = canvas.getContext("2d");
            //context.globalCompositeOperation = 'source-atop';
            //context.strokeStyle = "rgb(113, 113, 213)";
            context.strokeStyle = "#000";
            context.lineWidth = 0.6;
            context.beginPath();
            // Label end points
            //context.fillStyle = "rgb(0, 0, 0)";
            // Draw spline segemnts
            context.moveTo(points[0].x, points[0].y);
            for (var t = 0; t <= slideVal; t += 0.1) {
                context.lineTo(Math.pow(1 - t, 2) * points[0].x + 2 * (1 - t) * t * points[1].x + Math.pow(t, 2) * points[2].x, Math.pow(1 - t, 2) * points[0].y + 2 * (1 - t) * t * points[1].y + Math.pow(t, 2) * points[2].y);
            }

            // Stroke path
            context.stroke();
        }

        function drawSlopeCurve1(sID, maxValue) {
            // erase('canvasTwo');

            var canId = 'myCanvas4';
            var slideVal = parseInt(document.getElementById(sID).value);
            var canvas = document.getElementById(canId);
            var context = canvas.getContext('2d');
            canvas.width = canvas.width;
            //line end points
            x1 = 16;
            y1 = 170;
            x2 = 200;
            y2 = 80;

            //get slope (rise over run)
            var m = (y2 - y1) / (x2 - x1);
            //get y-intercept
            var b = y1 - (m * x1);
            //get distance between the two points
            var distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
            //get new x and y values
            var x = x1 + parseInt(distance / maxValue * slideVal);
            var y = parseInt(m * x + b);

            context.beginPath();
            context.moveTo(x1, y1);
            context.lineTo(x, y);
            context.lineWidth = 0.6;
            context.stroke();
        }

        function drawSlopeCurve2(sID, maxValue) {
            // erase('canvasTwo');

            var canId = 'myCanvas3';
            var slideVal = parseInt(document.getElementById(sID).value);
            var canvas = document.getElementById(canId);
            var context = canvas.getContext('2d');
            canvas.width = canvas.width;
            //line end points
            x1 = 16;
            y1 = 170;
            x2 = 160;
            y2 = 72;

            //get slope (rise over run)
            var m = (y2 - y1) / (x2 - x1);
            //get y-intercept
            var b = y1 - (m * x1);
            //get distance between the two points
            var distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
            //get new x and y values
            var x = x1 + parseInt(distance / maxValue * slideVal);
            var y = parseInt(m * x + b);

            context.beginPath();
            context.moveTo(x1, y1);
            context.lineTo(x, y);
            context.lineWidth = 0.6;
            context.stroke();
        }

    </script>
        </form>
    </body>
    </html>

提前致谢.我的 jsfiddle 链接:http://jsfiddle.net/g7hWD/1/

Thanks in Advance. my jsfiddle link: http://jsfiddle.net/g7hWD/1/

推荐答案

需要在函数drawSlopeCurve1()drawSlopeCurve2().最简单的方法是先修复函数 newSprite() 然后使用它(避免一遍又一遍地复制相同的代码块).

You need to add the drawing code at the very end of functions drawSlopeCurve1() and drawSlopeCurve2(). The simplest way is to fix function newSprite() first and then use it (to avoid copying identical code-blocks over and over).

在函数newSprite()中:

// Change that:
ctx.globalCompositeOperation = 'source-atop';

// To this:
ctx.globalCompositeOperation = "source-over";

(有关 globalCompositeOperation 的更多详细信息,请参阅 这里.)

(For more details on globalCompositeOperation see here.)

函数结束时drawSlopeCurve1/2():

// Append this:
newSprite(canId, x, y);

另请参阅此修改后的演示.

See, also, this modified demo.

这篇关于html5-canvas 在线移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5

CoffeeScript 总是以匿名函数返回
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)...
2024-04-20 前端开发问题
13