Creating Tilted Div and Object using JavaScript

2019-05-19 16:59发布

Is it possible to create such "tilted menu" (please see below) using JavaScript ?

Provided that I would like them to be "relative" to resize appropriately to a screen size.

enter image description here

2条回答
Anthone
2楼-- · 2019-05-19 17:25

This can be done using the <canvas> element of HTML5 and JQuery. By using the canvas element, you can draw parallelograms on top of one another with text in every other parallelogram.

This does have the drawback of needing to handle the clicks on each item by determining if it fell within one of the parallelograms, but it is the only way I know to do this.

HTML

<div id="click" width=10%>
Click Here
</div>
<div id="menu" width=10%>
  <canvas id="canvas"></canvas>
</div>

JQuery

$("#menu").hide();
$("#click").click(function(){
                     $("#menu").slideToggle('slow', function() {});
                   });

$("#canvas").click(function() {
                    // Determine which trapezoid the click was on and do the needed action.
                  });

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Draw the top parallelogram with the color blue.
ctx.fillStyle = "blue"; 
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(75,0);
ctx.lineTo(100,75);
ctx.lineTo(25,75);
ctx.lineTo(0,0);
ctx.fill();

// Use a point object here to make it a bit easier to determine the four points.
var startPoint = new Object();
startPoint.x = 25;
startPoint.y = 75;
// Draw the second parallelogram and fill it with grey.
ctx.fillStyle = "grey";
ctx.beginPath();
ctx.moveTo(startPoint.x, startPoint.y);
ctx.lineTo(startPoint.x + 75, startPoint.y);
ctx.lineTo(startPoint.x + 85, startPoint.y + 25);
ctx.lineTo(startPoint.x + 10, startPoint.y+25);
ctx.lineTo(startPoint.x, startPoint.y);
ctx.fill();

ctx.fillStyle = "black";
ctx.font = 'italic 22px sans-serif';
ctx.fillText("a", startPoint.x+10, startPoint.y+22); 

You can see this code working in this JSFiddle.

To keep sizes relative to the screen size, you will need to replace the hardcoded values with values determined by the size of the $("#menu") div.

You will also want to create a method to draw the parallelograms to make adding additional menu items much simpler.

查看更多
\"骚年 ilove
3楼-- · 2019-05-19 17:28

You can use CSS transforms do this, and with some other hacks ..

div
{

    transform:rotate(45deg);
    -ms-transform:rotate(45deg); /* IE 9 */
    filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1.5); /* IE 8- */
    -moz-transform:rotate(45deg); /* Firefox */
    -moz-transform:skewx(45deg) translatex(150px);
    -webkit-transform:rotate(45deg); /* Safari and Chrome */
    -o-transform:rotate(45deg); /* Opera */

}
查看更多
登录 后发表回答